package com.gxuwz.service.impl;

import java.util.List;

import com.gxuwz.annotation.RedisCache;
import com.gxuwz.entity.Purchase;
import com.gxuwz.mapper.PurchaseMapper;
import com.gxuwz.service.IPurchaseService;
import com.gxuwz.util.DateUtils;
import com.gxuwz.util.PrimaryUtils;
import com.gxuwz.util.SessionUtils;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 刘玉霜
 * @since 2017-10-27
 */
@Service
public class PurchaseServiceImpl extends ServiceImpl<PurchaseMapper, Purchase> implements IPurchaseService {

	@Autowired
	private PurchaseMapper purchaseDao;
	
	private int number = 1; // 编号
	private int day = DateUtils.getDay();

	private String createId() {
		// 第二天重置编号为1
		if (day != DateUtils.getDay()){
			day = DateUtils.getDay();
			number = 1;
		}
		String id = PrimaryUtils.getId("PURCHASE", number);		
		Purchase o = purchaseDao.selectById(id);
		// 如果能取得记录说明已经存在了
		while (o != null){
			number++;
			id = PrimaryUtils.getId("PURCHASE", number);
			o = purchaseDao.selectById(id);
		}
		return id;
	}
	
	@Override
	public Purchase createPurchase() {
		// 1.查询是否有未提交的采购单，如果有，返回该采购单
		Purchase o = new Purchase();

		o.setUserId(SessionUtils.getLoginUser().getId());
		// 标识为草稿
		o.setIsSubmit(0);

		List<Purchase> purchase = purchaseDao.select(o);
		
		if (purchase != null && purchase.size() > 0) {
			// 如果有草稿，直接返回草稿
			o = purchase.get(0); 
		} else {
			// 生成单号
			o.setId(createId());
			o.setCreateTime(DateUtils.getNowDefaultFormat());
			// 保存草稿
			purchaseDao.insert(o);
		}
		return o;
	}

	@Override
	public Integer modify(Purchase t) {
		Purchase dbPurchase = purchaseDao.selectById(t.getId());
		// 设置为正稿
		dbPurchase.setIsSubmit(1);
		// 设置为未入库
		dbPurchase.setIsStorage(0);
		return purchaseDao.updateAllColumnById(dbPurchase);
	}

	@Override
	@RedisCache(type = Page.class)
	public Page<Purchase> selectWithUser(Page<Purchase> page,Purchase t) {
		// 查询当前登录用户的采购单
		t.setUserId(SessionUtils.getLoginUser().getId());
		// 设置为正稿
		t.setIsSubmit(1);
		return page.setRecords(purchaseDao.selectWithUser(page, t));
	}
	
}
